package com.platform.helper.network;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * describe:
 *
 * @author rainly
 * @date 2019/12/11
 * @time 11:32 上午
 */
public class BaseNetworkUtil {

    /**
     * 通过http的Post方式，入参方式是 Body raw形式的 json
     *
     * @param url             url路径
     * @param paramJSONString json格式的入参数据
     * @param mediaType       从MediaType类中选择
     * @param charset         从StandardCharsets类中选择
     * @return
     */
    public static String httpPostByBodyRow(String url, String paramJSONString, MediaType mediaType, Charset charset) {
        String contentType = mediaType.getType() + "/" + mediaType.getSubtype();
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-type", contentType);
            post.setEntity(new StringEntity(paramJSONString, charset));
            CloseableHttpResponse response = httpClient.execute(post);
            HttpEntity responseEntity = response.getEntity();
            return EntityUtils.toString(responseEntity);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过http的Post方式，入参方式是 Body raw形式的 json
     *
     * @param url
     * @param paramJSONString
     * @param contentType
     * @param charset
     * @return
     */
    public static String httpPostByBodyRow(String url, String paramJSONString, String contentType, String charset) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-type", contentType);
            post.setEntity(new StringEntity(paramJSONString, charset));
            CloseableHttpResponse response = httpClient.execute(post);
            HttpEntity responseEntity = response.getEntity();
            return EntityUtils.toString(responseEntity);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
